package com.cygsunri.report.service.mediator;

import com.cygsunri.report.entity.GeneralReport;
import com.cygsunri.report.entity.ReportElement;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 抽象表格中介器
 */
public abstract class AbstractReportMediator {
    protected static Logger logger = LoggerFactory.getLogger(AbstractReportMediator.class);
    private AbstractReportMediator subMediator = null;
    private ObjectMapper mapper = new ObjectMapper();

    public int mediate(GeneralReport report, Workbook workbook) {
        int result = mediateInner(report, workbook);

        if (result == 0 && subMediator != null) {
            result = subMediator.mediate(report, workbook);
        }

        return result;
    }

    protected abstract int mediateInner(GeneralReport report, Workbook workbook);

    /**
     * 把单元格中存储的字符串转换为
     * @param str 单元格中存储的字符串
     * @return ReportElement 单元格描述结构
     */
    ReportElement makeElement(String str) {
        Preconditions.checkNotNull(str);

        str = str.trim();
        ReportElement element = null;

        try {
            element = mapper.readValue(str, ReportElement.class);
        } catch (IOException ignored) {
            logger.debug("JSON转换错误 = {}", ignored.getMessage());
        }

        return element;
    }

    /**
     * 把报表元素在转换成字符串
     * @param element 报表元素
     * @return 元素字符串
     */
    String makeString(ReportElement element) {
        Preconditions.checkNotNull(element);
        try {
            return mapper.writeValueAsString(element);
        } catch (JsonProcessingException e) {
            return "";
        }
    }

    /**
     * 设置单元格的值
     * @param sheet 表格
     * @param iRow 行序号
     * @param iCol 列序号
     * @param value 单元格的值
     * @return Cell 新增的单元格
     */
    void setCell(Sheet sheet, int iRow, int iCol, String value) {
        Row row = sheet.getRow(iRow);

        if (row == null) {
            row = sheet.createRow(iRow);
        }

        Cell cell = row.getCell(iCol, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        cell.setCellValue(value);
    }

    public AbstractReportMediator getSubMediator() {
        return subMediator;
    }

    private void setSubMediator(AbstractReportMediator subMediator) {
        this.subMediator = subMediator;
    }

    AbstractReportMediator subMediator(AbstractReportMediator subMediator) {
        Preconditions.checkNotNull(subMediator);
        this.setSubMediator(subMediator);
        return subMediator;
    }
}
